package com.jiangnan.ui.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.jiangnan.R
import com.jiangnan.databinding.ItemCommentBinding
import com.jiangnan.databinding.ItemSubCommentBinding
import com.jiangnan.entity.CommentResponse

class CommentsAdapter(
  private val currentUserId: Long,
  private val onReply: (parentId: Long, toUserId: Long, toUserName: String) -> Unit,
  private val onDelete: (commentId: Long) -> Unit
) : RecyclerView.Adapter<CommentsAdapter.VH>() {

  private val data = mutableListOf<CommentResponse>()

  fun submit(list: List<CommentResponse>) {
    data.apply {
      clear()
      addAll(list)
    }
    notifyDataSetChanged()
  }

  inner class VH(val b: ItemCommentBinding) : RecyclerView.ViewHolder(b.root) {
    init {
      b.root.setOnLongClickListener {
        val pos = adapterPosition
        if (pos != RecyclerView.NO_POSITION) {
          onDelete(data[pos].id)
        }
        true
      }
    }
  }

  override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH {
    val binding = ItemCommentBinding.inflate(
      LayoutInflater.from(parent.context),
      parent,
      false
    )
    return VH(binding)
  }

  override fun getItemCount(): Int = data.size

  override fun onBindViewHolder(holder: VH, position: Int) {
    val comment = data[position]
    val b = holder.b

    // ── 根评论部分 ───────────────────────────────────

    // 1. 头像
    Glide.with(b.ivAvatar)
      .load(comment.userAvatar)
      .placeholder(R.drawable.img_default)
      .circleCrop()
      .into(b.ivAvatar)

    // 2. 昵称／时间／内容
    b.tvNickname.text = comment.userNickname
    b.tvTime.text = comment.createdAt.substring(0, 16).replace('T', ' ')
    b.tvContent.text = if (comment.toUserNickname != null)
      "回复 @${comment.toUserNickname}：${comment.content}"
    else
      comment.content

    // 3. 点击回复根评论
    b.tvContent.setOnClickListener {
      onReply(comment.id, comment.userId, comment.userNickname)
    }

    // ── 子回复部分 ───────────────────────────────────

    b.llReplies.removeAllViews()
    if (comment.replies.isNotEmpty()) {
      b.llReplies.visibility = ViewGroup.VISIBLE

      comment.replies.forEach { reply ->
        // Inflate 子回复专用布局
        val subB = ItemSubCommentBinding.inflate(
          LayoutInflater.from(b.llReplies.context),
          b.llReplies,
          false
        )
        // 头像
        Glide.with(subB.ivSubAvatar)
          .load(reply.userAvatar)
          .placeholder(R.drawable.img_default)
          .circleCrop()
          .into(subB.ivSubAvatar)

        // 昵称：如果 toUserNickname 不空，则显示 “user 回复>toUser”
//        subB.tvSubNickname.text = if (reply.toUserNickname != null) {
//          "${reply.userNickname} 回复> ${reply.toUserNickname}"
//        } else {
//          reply.userNickname
//        }
        subB.tvSubNickname.setText("${reply.userNickname}")
        // 时间
//        subB.tvSubTime.text = reply.createdAt.substring(0, 16).replace('T', ' ')
        subB.tvSubTime.setText(reply.createdAt.substring(0, 16).replace('T', ' '))
        // 内容
//        subB.tvSubContent.text = if (reply.toUserNickname != null) {
//          "回复 @${reply.toUserNickname}：${reply.content}"
//        } else {
//          reply.content
//        }
        subB.tvSubContent.setText("回复 @${reply.toUserNickname}：${reply.content}")

        // 点击回复子评论
        subB.tvSubContent.setOnClickListener {
          onReply(comment.id, reply.userId, reply.userNickname)
        }
        // 长按删除子评论
        subB.root.setOnLongClickListener {
          onDelete(reply.id)
          true
        }

        b.llReplies.addView(subB.root)
      }
    } else {
      b.llReplies.visibility = ViewGroup.GONE
    }
  }
}